import cookie from 'js-cookie'
import request from './request'

/**
 * 本地读取token
 * 优先读取cookie中，cookie->localStorage
 */
export function getToken() {
  return cookie.get('jwtToken')
  //  || localStorage.getItem("jwtToken");
}

/**
 * 清空token
 * @param {Boolean} removeAxiosHeader 是否设置全局axios头信息为空，默认为false
 */
export function removeToken(removeAxiosHeader = false) {
  cookie.remove('jwtToken')
  // localStorage.removeItem("jwtToken");
  removeAxiosHeader && request.setToken('')
}

/**
 * 存储token，在cookie，localStorage中同时存储
 * @param {String} token
 * @param {Boolean} setAxios 设置全局axios头信息带上token，默认为true
 * @param {Boolean} clearMode 是否在调用设置token的时候，若异常情况为空值，则清空已有存储，默认为true
 *
 */
export function setToken(
  token: string | undefined,
  setAxios = true,
  clearMode = false
) {
  if (clearMode) {
    removeToken()
  }
  if (token) {
    // window.localStorage.setItem("jwtToken", token);
    cookie.set('jwtToken', token)
    setAxios && request.setToken(token)
  }
}
